﻿namespace MiniCore;

public class HttpListenerServer : IServer
{
    private readonly HttpListener _httpListener;
    private readonly string[] _urls;

    public HttpListenerServer(params string[] urls)
    {
        _httpListener = new HttpListener();
        _urls = urls.Any() ? urls : new string[] { "http://localhost:5000/" };
    }

    /// <summary>
    /// WebHost构建的管道由Server和HttpHandler构成
    /// </summary>    
    public async Task StartAsync(RequestDelegate hander)
    {
        Array.ForEach(_urls, url => _httpListener.Prefixes.Add(url));
        // 构建服务
        _httpListener.Start();
        Console.WriteLine("Server started and is listening on: {0}", string.Join(';', _urls));
        while (true)
        {
            #region 监听HttpListenerContext并转换成HttpContext
            // HttpListener接收到请求之后同行会创建一个自己的上下文对象
            // HttpListenerContext是HttpContext承载的上下文信息最初来源
            HttpListenerContext? listenerContext = await _httpListener.GetContextAsync();
            // 创建HttpListenerFeature对象，将HttpListenerContext的信息转换到该对象来
            HttpListenerFeature? feature = new HttpListenerFeature(listenerContext);
            // 创建适配器集合把HttpListenerFeature中的属性存到IFeatureCollection中
            IFeatureCollection? features = new FeatureCollection()
                .Set<IHttpRequestFeature>(feature)
                .Set<IHttpResponseFeature>(feature);
            // 取IFeatureCollection中的request和response数据，并初始化HttpContext
            var httpContext = new HttpContext(features);
            #endregion

            // 中间件处理HttpContext
            await hander(httpContext);
            listenerContext.Response.Close();
        }
    }
}
